﻿// 可拖拽的插件
import draggable from 'vuedraggable'
import { settingsItem } from './componentsItem.js'
import BiItem from './BiItem.vue'
import BiData from './BiData.vue'
import BiConfig from './BiConfig.vue'
import BiPreview from './BiPreview.vue'
export default {
  components: {
    draggable, BiItem, BiData, BiConfig, BiPreview
  },
  data () {
    return {
      loading: false,
      settingsItem, // 相关的组件变量
      biDashboardInfo: null, // 保存仪表板的配置信息
      // 页面配置的变量
      formData: {
        // 页面组件的组成
        list: []
      },
      // 选中的元素
      selectFormItem: null,
      currentTabs: 'itemStyle',
      // 预览时
      previewVisible: false,
      previewSettings: null
    }
  },
  created () {
    if (this.$route.query.uid) {
      this.getBasicInfoByUid(this.$route.query.uid)
    } else {
      this.$alert('没有获取到当前仪表板的Uid', '提示', {
        confirmButtonText: '确定',
        callback: () => {
          this.$router.go(-1)
        }
      })
    }
  },
  methods: {
    // 返回时
    returnBack () {
      this.$confirm('确定离开当前页面?', '提示', {
        confirmButtonText: '确定',
        cancelButtonClass: 'el-button--info',
        cancelButtonText: '取消'
      }).then(() => {
        this.$router.go(-1)
      }).catch(() => {})
    },
    // 获取基础的配置信息
    getBasicInfoByUid (uid) {
      this.loading = true
      this.$get('/bi_dashboard/detail', {
        id: uid
      }).then(data => {
        let dataResult = data.data.result
        if (dataResult.code === 'success') {
          this.biDashboardInfo = dataResult.data
          if (dataResult.data.settings_json) {
            this.formData = JSON.parse(dataResult.data.settings_json)
            if (this.formData.list.length) {
              this.selectFormItem = this.formData.list[0]
            } else {
              this.selectFormItem = null
            }
          }
        } else {
          this.$message({
            message: dataResult.msg,
            type: 'warning'
          })
        }
        this.loading = false
      })
    },
    // 点击确定时
    submitForm () {
      if (this.biDashboardInfo && this.biDashboardInfo.uid) {
        console.log(this.formData)
        this.$confirm('确定保存当前配置信息?', '提示', {
          confirmButtonText: '确定',
          cancelButtonClass: 'el-button--info',
          cancelButtonText: '取消'
        }).then(() => {
          this.editMethod()
        }).catch(() => {})
      }
    },
    // 保存的方法
    editMethod () {
      this.loading = true
      this.$patch('/icpbidashboard/' + this.biDashboardInfo.uid, {
        title: this.biDashboardInfo.title,
        desc: this.biDashboardInfo.desc,
        route: this.biDashboardInfo.route,
        settings_json: JSON.stringify(this.formData)
      }).then((data) => {
        let dataResult = data.data.result
        if (dataResult.code === 'success') {
          this.$message({
            message: '保存成功',
            type: 'success'
          })
        } else {
          this.$message({
            message: dataResult.msg,
            type: 'warning'
          })
        }
        this.loading = false
      })
    },
    // 预览
    previewForm () {
      this.previewSettings = JSON.stringify(this.formData)
      this.previewVisible = true
    },
    // 添加组件时
    handleEchartItemAdd (evt) {
      const newIndex = evt.newIndex
      // 为拖拽到容器的元素添加唯一 key
      const key = Date.parse(new Date()) + '_' + Math.ceil(Math.random() * 999999)
      let cloneObj = JSON.parse(JSON.stringify(evt.item._underlying_vm_))
      cloneObj['key'] = key
      cloneObj['model'] = cloneObj.model ? cloneObj.model : (cloneObj.type + '_' + key)
      this.$set(this.formData.list, newIndex, cloneObj)
      this.selectFormItem = this.formData.list[newIndex]
    },
    // 添加到栅格中时
    handleFormItemColAdd ($event, row, colIndex) {
      const newIndex = $event.newIndex
      const oldIndex = $event.oldIndex
      const item = $event.item
      // 防止布局元素的嵌套拖拽(栅格中不能嵌套栅格和tabs)
      if (item.className.indexOf('data-grid') >= 0 || item.className.indexOf('tabs-grid') >= 0) {
        // 如果是列表中拖拽的元素需要还原到原来位置
        item.tagName === 'DIV' && this.formData.list.splice(oldIndex, 0, row.columns[colIndex].list[newIndex])
        row.columns[colIndex].list.splice(newIndex, 1)
        return false
      }
      const key = Date.parse(new Date()) + '_' + Math.ceil(Math.random() * 999999)
      let cloneObj = JSON.parse(JSON.stringify(item._underlying_vm_))
      cloneObj['key'] = key
      cloneObj['model'] = cloneObj.model ? cloneObj.model : (cloneObj.type + '_' + key)
      this.$set(row.columns[colIndex].list, newIndex, cloneObj)
      this.selectFormItem = row.columns[colIndex].list[newIndex]
    },
    // tab中添加内容
    handleFormItemTabAdd ($event, tab, tabIndex) {
      const newIndex = $event.newIndex
      const oldIndex = $event.oldIndex
      const item = $event.item
      // 防止布局元素的嵌套拖拽--不能嵌套tabs
      if (item.className.indexOf('tabs-grid') >= 0) {
        // 如果是列表中拖拽的元素需要还原到原来位置
        item.tagName === 'DIV' && this.formData.list.splice(oldIndex, 0, tab.tabList[tabIndex].list[newIndex])
        tab.tabList[tabIndex].list.splice(newIndex, 1)
        return false
      }
      const key = Date.parse(new Date()) + '_' + Math.ceil(Math.random() * 999999)
      let cloneObj = JSON.parse(JSON.stringify(item._underlying_vm_))
      cloneObj['key'] = key
      cloneObj['model'] = cloneObj.model ? cloneObj.model : (cloneObj.type + '_' + key)
      this.$set(tab.tabList[tabIndex].list, newIndex, cloneObj)
      this.selectFormItem = tab.tabList[tabIndex].list[newIndex]
    },
    // 删除tabs中的元素时
    handleFormTabsItemDelete (elIndex, tabIndex, i) {
      if (this.formData.list[elIndex].tabList[tabIndex].list.length - 1 === i) {
        if (i === 0) {
          this.selectFormItem = {}
        } else {
          this.selectFormItem = this.formData.list[elIndex].tabList[tabIndex].list[i - 1]
        }
      } else {
        this.selectFormItem = this.formData.list[elIndex].tabList[tabIndex].list[i + 1]
      }
      this.$nextTick(() => {
        this.formData.list[elIndex].tabList[tabIndex].list.splice(i, 1)
      })
    },
    // 选中单个元素时
    handleSelectFormItem (index) {
      this.selectFormItem = this.formData.list[index]
    },
    // 选中tabs中的元素时
    handleSelectTabsFormItem (elIndex, tabIndex, i) {
      this.selectFormItem = this.formData.list[elIndex].tabList[tabIndex].list[i]
    },
    // 点击删除时
    handleFormItemDelete (index) {
      if (this.formData.list.length - 1 === index) {
        if (index === 0) {
          this.selectFormItem = {}
        } else {
          this.selectFormItem = this.formData.list[index - 1]
        }
      } else {
        this.selectFormItem = this.formData.list[index + 1]
      }
      this.$nextTick(() => {
        this.formData.list.splice(index, 1)
      })
    }
  },
  watch: {
    // 选中的元素变化时
    selectFormItem: {
      handler: function (val, oldVal) {
        if (val && (val.type === 'grid' || val.type === 'tabs')) {
          this.currentTabs = 'itemStyle'
        }
      },
      deep: true
    }
  }
}
